import { getOpenidList, getSheetAllData, sendMsg } from '@/api/daily';
import { ResultCodeEnum } from '@/enums';
import { formatDate, getStartOrEndDate } from '@/utils/date';
import dayjs from 'dayjs';
import { useToast } from 'wot-design-uni';
import { isString } from 'wot-design-uni/components/common/util';

export const useFetchAllSheetData = () => {
  type TDataItem = {
    date: string;
    percent: number | string;
  };

  const getCurrentWeekDates = (): string[] => {
    const { start } = getStartOrEndDate('week'); // 获取当前周的第一天（周一）
    const dates = [];
    for (let i = 0; i < 5; i++) {
      dates.push(dayjs(start).add(i, 'day').format('YYYY-MM-DD')); // 按天递增
    }
    return dates;
  };

  const weekDateList = getCurrentWeekDates();

  const dataList = ref<TDataItem[]>([]);
  const allSheetData = ref<any>([]);

  const getData = async () => {
    dataList.value = [];
    allSheetData.value = [];
    const res = await getSheetAllData();
    if (res.code === ResultCodeEnum.SUCCESS) {
      allSheetData.value = res.data;
      const { sheetData, _dateRowIndex, nameColIndex } = res.data;
      sheetData.forEach((row: any) => {
        if (weekDateList.includes(formatDate(row[0]))) {
          dataList.value.push({
            date: formatDate(row[0]),
            percent: isString(row[nameColIndex])
              ? row[nameColIndex]
              : row[nameColIndex] * 100 + '%'
          });
        }
      });
    }
  };

  const nameList = ref<string[]>([]);
  const findNoCheckInList = () => {
    nameList.value = [];
    const { sheetData, dateRowIndex, _nameColIndex } = allSheetData.value;
    const dateData = sheetData[dateRowIndex];
    const nameData = sheetData[1];
    console.log('打印***dateData', dateData);
    console.log('打印***nameData', nameData);
    for (let index = 1; index < dateData.length; index++) {
      const percent = dateData[index];
      if (!percent) {
        nameList.value.push(nameData[index] as string);
      }
    }
    console.log('打印***nameList', nameList);
    nameList.value = nameList.value.filter(
      (item) => Boolean(item) && item !== 'admin'
    );
  };

  const { success } = useToast();
  const handleSendMsg = async () => {
    const nameRes = await getOpenidList(nameList.value.join(','));
    if (nameRes.code === ResultCodeEnum.SUCCESS) {
      const res = await sendMsg(nameRes.data);
      if (res.code === ResultCodeEnum.SUCCESS) {
        success({
          msg: '提醒成功'
        });
      }
    }
  };

  return {
    dataList,
    allSheetData,
    nameList,
    weekDateList,
    getData,
    findNoCheckInList,
    handleSendMsg
  };
};
